package co.edu.uniandes.distribuidos.fss.service;

import java.io.IOException;

import net.jxta.discovery.DiscoveryService;
import net.jxta.document.Advertisement;
import net.jxta.document.MimeMediaType;
import net.jxta.endpoint.EndpointAddress;
import net.jxta.endpoint.EndpointListener;
import net.jxta.endpoint.Message;
import net.jxta.endpoint.MessageElement;
import net.jxta.exception.PeerGroupException;
import net.jxta.id.ID;
import net.jxta.peergroup.PeerGroup;
import net.jxta.platform.Application;
import net.jxta.protocol.ResolverQueryMsg;
import net.jxta.protocol.ResolverResponseMsg;
import net.jxta.resolver.QueryHandler;
import co.edu.uniandes.distribuidos.fss.adv.FileAdvertisement;
import co.edu.uniandes.distribuidos.fss.file.SharedFile;
import co.edu.uniandes.distribuidos.peer.Peer;

public class FileSharingService implements Application,EndpointListener,QueryHandler{

	public static final String HANDLER_NAME = "FileSharingQueryHandler";
	public static String serviceName = "FileSharingService";
	
	public static final String LIST_REQUEST = "LIST_REQ";
    public static final String LIST_RESULT = "LIST_RES";
    public static final String GET_REQUEST = "GET_REQ";
    public static final String GET_RESULT = "GET_RES";

    public static final String MESSAGE_TYPE = "msgType";
	public static String ADDRRES = "address";
	public static final String ID = "ID";
	public static final String REQUEST_ID = "RID";
    public static final String RETURN_ADDRESS = "RTN_ADR";
    public static final String CONTENT_ADVERTISEMENT = "CADV";
    public static final String CONTENT_LENGTH = "CLEN";
    public static final String ADVERTISEMENT_COUNT = "COUNT";
    public static final String CHUNK_OFFSET = "OFFSET";
    public static final String CHUNK_SIZE = "SIZE";
    public static final String CHUNK_DATA = "DATA";
    public static final String RANGE_BEGIN = "RANGE_BEGIN";
    public static final String RANGE_END = "RANGE_END";
	
	public static MimeMediaType MIMEMEDIATYPE= new MimeMediaType("text", "xml");
	private PeerGroup peerGroup;
	@Override
	public void init(PeerGroup group, ID id, Advertisement adv)
			throws PeerGroupException {
		this.peerGroup=group;
	}

	@Override
	public int startApp(String[] arg0) {
		peerGroup.getEndpointService().addIncomingMessageListener(this, serviceName, null);
		return 0;
	}

	@Override
	public void stopApp() {
		
	}

	public void publishFile(SharedFile publishedFile) throws Exception {
		   if (publishedFile == null) {
	            return;
	        }

	        DiscoveryService discoveryService = this.peerGroup.getDiscoveryService();

	        try {
	            FileAdvertisement adv = publishedFile.getAdvertisement();
	            System.out.println(adv);
	            discoveryService.publish (adv);

	        } catch (Exception ex) {
	            System.err.println ("Can't publish file advertisement: " + ex);
	            throw ex;
	        }
		
	}
	
	   /**
     * Returns the endpoint address for this service.
     *
     * @return String the endpoint address.
     *
     */
    public String getEndpointAddress() {
        return "jxta://" + Peer.getPeerId(peerGroup) +
               "/" + serviceName +
               "/" + getGroupId(peerGroup);
    }
    
    /**
     * Returns the String version of the groupId for the given group.
     *
     * @return String groupId for the given group
     *
     */
    public static String getGroupId(PeerGroup group) {
        // XXX  20011105    bondolo@jxta.org why not just use the urn value?
        return group.getPeerGroupID().getUniqueValue().toString();
    }
    
    

	@Override
	public int processQuery(ResolverQueryMsg query) {
		String queryStr = query.getQuery();
		System.out.println(queryStr);
		return 0;
	}

	@Override
	public void processResponse(ResolverResponseMsg response) {
		System.out.println("received response: "+response.getResponse());
		
	}

	@Override
	public void processIncomingMessage(Message message, EndpointAddress srcAddr,
			EndpointAddress destAddr) {
		System.out.println("Endpoint Sharing file............");
		
	}
	 /**
     * Returns the String contained in the given tag in the given Message.
     *
     * @return String from given tag in given message.
     *
     */
    public static String popString(Message message, String tag) throws IOException {
        MessageElement substrQueryEl = message.getMessageElement(tag);
        if(substrQueryEl == null) {
            return "";
        }
        return substrQueryEl.toString();
    }
}
